package com.javasea.web.httpclient.okhttp;

import com.fasterxml.jackson.databind.JsonNode;
import com.javasea.web.httpclient.httpclient.HttpClientUtils;
import com.javasea.web.httpclient.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@ClassName OkhttpDemo
 *@Description TODO
 *@Author longxiaonan@163.com
 *@Date 2020/12/15 0015 13:14
 */
@Slf4j
public class OkhttpUtils {

    /**
     * @Author lsc
     * <p>get 请求 </p>
     * @Param [url]
     * @Return
     */
    public static void get(String url){
        Call call = getCall(url);
        // 4异步调用,并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
                System.out.println(call);
            }

            @Override
            public void onResponse(Call call, final Response response) {
                if (response!=null && response.isSuccessful()){
                    // ...
                    // response.body().string();
                    System.out.println(call);
                }
            }
        });
    }

    public static String getSync(String url){
        //同步调用,返回Response,会抛出IO异常
        Call call = getCall(url);
        try {
            Response response = call.execute();
            ResponseBody body = response.body();
            //response.body().toString()：  返回Response对象然后把转换为String
            // okhttp3.internal.http.RealResponseBody@4516af24
            String s = body.toString();
            //response.body().string()： 返回Response对象的ResponseBody对象的内容；
            // {"type":"FeatureCollection","features":
            // [{"type":"Feature","properties":{"adcode":110000,"name":"北京市","center": ...}
            String string = body.string();
            return string;
        } catch (IOException e) {
            log.error("GET请求失败，url:[{}]", url, e);
        }
        return null;
    }

    private static Call getCall(String url) {
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2设置请求
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        // 3封装call
        return client.newCall(request);
    }


    /**
     * @Author lsc
     * <p>post 请求 ，json参数 </p>
     * @Param [url, json]
     * @Return
     */
    public void postForJson(String url, String json){
        // 1 获取OkHttpClient对象
        Call call = getCall(url, json);
        // 5 异步调用
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response!=null && response.isSuccessful()){
                    // ...
                }
            }
        });
    }

    /**
     * @Author lsc
     * <p>post 请求 ，json参数 </p>
     * @Param [url, json]
     * @Return
     */
    public static String postForJsonSync(String url, String json){
        Call call = getCall(url, json);
        try{
            Response response = call.execute();
            ResponseBody body = response.body();
            String string = body.string();
            return string;
        }catch (Exception e){
            log.error("POST请求失败，url:[{}]", url);
        }
        return null;
    }

    private static Call getCall(String url, String json) {
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2 构建参数
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        // 3 构建 request
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        // 4 将Request封装为Call
        return client.newCall(request);
    }

    @Test
    public void testGet(){
        String url = "https://geo.datav.aliyun.com/areas/bound/100000_full.json";
        String result = OkhttpUtils.getSync(url);
        JsonNode jsonNode = JacksonUtils.json2Node(result);
        System.out.println(jsonNode);
        JsonNode features = jsonNode.get("features");
        features.forEach(b -> {
            JsonNode properties = b.get("properties");
            JsonNode adcode1 = properties.get("adcode");
            String s = String.valueOf(adcode1);
            System.out.println(s);
        });
    }


    @Test
    public void testPost(){
        /**
         @GetMapping("/postTest")
         public String sayHello(@RequestBody Map<String, List<String>> map){
         System.out.println(map);
         return "hello";
         }
         */
        String url = "http://localhost:8082/postTest";
        Map<String, List> map = new HashMap<>();
        List list = new ArrayList();
        list.add("a1");
        list.add("a2");
        map.put("aa", list);
        String s = JacksonUtils.obj2json(map);
        String result = OkhttpUtils.postForJsonSync(url, s);
        System.out.println(result);
    }

}
